var Excel = require('exceljs');

module.exports = exports = {}

let border = {
    top: { style: 'thin', color: { argb: 'FF0D0D0D' } },
    left: { style: 'thin', color: { argb: 'FF0D0D0D' } },
    bottom: { style: 'thin', color: { argb: 'FF0D0D0D' } },
    right: { style: 'thin', color: { argb: 'FF0D0D0D' } }
}

exports.exportXls = async ({ columns, data, filename }) => {

    var m = [];

    // 获取字段列
    let id_fields = []

    // 表头行
    let header_rows = []

    // 合并行
    let range = []

    // 遍历列
    columns.forEach((row, y) => {

        let header_row = []

        row.forEach((cell, x) => {

            cell.colspan = cell.colspan | 0
            cell.rowspan = cell.rowspan | 0
            let tx, ty
            let cspan = cell.colspan ? cell.colspan : 1;
            let rspan = cell.rowspan ? cell.rowspan : 1;
            for (; m[y] && m[y][x]; ++x);  //skip already occupied cells in current row
            for (tx = x; tx < x + cspan; ++tx) {  //mark matrix elements occupied by current cell with true
                for (ty = y; ty < y + rspan; ++ty) {
                    if (!m[ty]) {  //fill missing rows
                        m[ty] = [];
                    }
                    m[ty][tx] = true;
                }
            }
            cell.top = y
            cell.left = x

            // 增加表头占用的行
            header_row[x] = cell.header

            // 设置合并单元格信息
            if (cell.rowspan || cell.colspan) {

                range.push({
                    s: {//s为开始
                        c: cell.left,//开始列
                        r: cell.top //开始取值范围
                    },
                    e: {//e结束
                        c: cell.colspan ? cell.left + cell.colspan - 1 : cell.left,//结束列
                        r: cell.rowspan ? cell.top + cell.rowspan - 1 : cell.top //结束范围
                    }
                })
            }

            if (cell.key) {
                id_fields.push({
                    key: cell.key,
                    header: cell.header,
                    width: cell.width,
                    field_style: cell.field_style,
                    left: x,
                })
            }
        })

        header_rows.push(header_row)

    })

    // 定义sheet
    var workbook = new Excel.Workbook();

    var worksheet = workbook.addWorksheet('Sheet1');

    // 设置字段列，方便批量写入数据
    worksheet.columns = id_fields.sort((a, b) => {
        return a.left > b.left ? 1 : -1
    })

    // 渲染表头 把每行表头补到指定的长度，防止出现列错乱的情况
    header_rows.forEach(v => {
        let len = v.length
        for (let i = 0; i < len; i++) {
            if (!v[i]) v[i] = null
        }
        for (let i = len; i < id_fields.length; i++) {
            v.push(null)
        }
    })

    // 增加表头数据
    worksheet.addRows(header_rows)

    // 增加内容行
    worksheet.addRows(data)

    // 移除第一行,默认标题行
    worksheet.spliceRows(0, 1)

    // 设置合并单元格
    range.forEach(v => {
        let col1 = String.fromCharCode(65 + v.s.c) + (v.s.r + 1)
        let col2 = String.fromCharCode(65 + v.e.c) + (v.e.r + 1)
        worksheet.mergeCells(`${col1}:${col2}`);
    })

    // 设置表头样式
    columns.forEach(row => {

        row.forEach(v => {
            let col = String.fromCharCode(65 + v.left) + (v.top + 1)
            let cell = worksheet.getCell(col)

            if (v.style && v.style.border) {
                v.style.border = border
            }
            Object.assign(cell.style, v.style)

        })

    })

    // 设置数据单元格样式
    let last_row_num = worksheet.rowCount
    let cell_count = worksheet.columnCount
    for (let i = columns.length + 1; i <= last_row_num; i++) {

        id_fields.forEach((v, j) => {
            let cell = worksheet.getCell(i, j + 1)
            cell.border = border

            Object.assign(cell.style, v.field_style)

        })

    }


    let buf = await workbook.xlsx.writeBuffer()
    return buf
}